const app = getApp()
import { payKeyboardAsync } from '../payKeyboard/PayKeyboardAsync'
import logs from '../../utils/logs'
module.exports = Behavior({
  data: {
    // 支付密码弹窗
    popupSpecs: false,
    // 支付中
    isPayClick: false,
    // 接口请求状态
    loading: false,
    // 验证支付定时器
    Interval: null
  },
  methods: {
    /**
     * 支付
     * 调用前需要设置余额 || 微信支付参数及支付成功跳转页面地址：balancePayParames || WeChatPayParames || redirectPath
     * @param {Object} btn 支付方式数据
     */
    handlePay: async function(btn) {
      // 控制支付请求多次
      if (this.data.isPayClick) {
        app.tips("还在请求支付，请等待~")
        return
      }
      this.data.isPayClick = true

      // 支付方式值：3-余额支付, 55-微信支付
      const payType = btn.value
      // 余额支付
      if (payType == 3) {
        // 是否开启余额密码支付
        const { need_password } = btn.other
        if (need_password) { // if (true) { 
          // 获取输入的密码
          const pass = await this.getPayKeyboardPassword()
          // 请求密码验证接口
          this.getVerifyPassword(pass)
        } else {
          // 无密码
          this.balancePay("");
        }
      } 
      // 微信支付
      else if (payType == 55) {
        this.getWeChatPayParams()
      }
    },

    /**
     * 余额支付密码相关，具体功能未清楚
     * @param {}} evt 
     */
    payKeyboardComplete(evt) {
      this.setData({
        popupSpecs: false
      });
      payKeyboardAsync.complete(evt.detail);
    },

    /**
     * 获取输入的密码
     * @returns {Promise}
     */
    getPayKeyboardPassword() {
      this.setData({
        popupSpecs: true
      });
      return new Promise((resove, reject) => {
        payKeyboardAsync.addCompleteFn((pass) => {
          resove(pass);
        });
      });
    },

    /**
     * 关闭输入密码弹窗
     */
    payKeyboardClose() {
      this.setData({ popupSpecs: false });
      this.data.isPayClick = false;
    },

    /**
     * 验证密码
     * @param {String} pass 密码
     */
    getVerifyPassword: function(pass) {
      wx.showLoading({ title: '验证密码...' })
      const urlStr = app.getNetAddresss("payment.password.check")
      const _this = this
      app._getNetWork({
        url: urlStr,
        data: { password: pass },
        success: function(res) {
          const resData = res.data
          if (resData.result == 1) {
            // 密码验证通过，继续支付
            _this.balancePay()
          } else {
            _this.data.isPayClick = false
            app.tips(resData.msg || '密码验证失败！')
          }
        },
        complete: function() {
          wx.hideLoading()
        },
      })
    },

    /**
     * 余额支付
     */
    balancePay: function() {
      let { balancePayRoute, balancePayParames } = this.data
      const urlStr = app.getNetAddresss(balancePayRoute)
      let data = {...balancePayParames}
      const _this = this
      wx.showLoading({ title: '支付中...' })
      app._postNetWork({
        url: urlStr,
        data,
        success: function(res) {
          const resData = res.data
          if (resData.result == 1) {
            _this.checkPay()
          } else {
            _this.data.isPayClick = false
            setTimeout(() => {
              app.tips(resData.msg || '支付失败！')
            })
          }
        },
        complete: function() {
          wx.hideLoading()
        }
      })
    },

    /**
     * 验证支付是否成功
     */
    checkPay: function() {
      let { ckeckPayRoute, balancePayParames, Interval } = this.data
      const urlStr = app.getNetAddresss(ckeckPayRoute)
      let data = {...balancePayParames}
      this.setData({ loading: true })
      const _this = this
      app._postNetWork({
        url: urlStr,
        data,
        success: function(res) {
          const resData = res.data
          if (resData.result == 1 && resData.data?.status == 1) {
            clearInterval(Interval)
            _this.data.Interval = null
            _this.setData({ loading: false })
            wx.showModal({
              title: '成功',
              content: '支付成功',
              showCancel: false,
              complete: (resC) => {
                if (resC.confirm) {
                  _this.toRedirect()
                }
              }
            })
          } else {
            if (!Interval) {
              _this.data.Interval = setInterval(() => {
                _this.checkPay();
              }, 1000);
            }
          }
        }
      })
    },

    /**
     * 获取微信支付参数
     */
    getWeChatPayParams: function() {
      const { WeChatPayRoute, WeChatPayParames } = this.data
      const urlStr = app.getNetAddresss(WeChatPayRoute)
      let data = {...WeChatPayParames}
      const _this = this
      wx.showLoading({ title: '支付中...' })
      app._postNetWork({
        url: urlStr,
        data,
        success: function(res) {
          const resData = res.data
          if (resData.result == 1) {
            const { config, redirect } = resData.data
            if (config) {
              _this.WeChatPay(config, redirect)
            }
          } else {
            app.tips(resData.msg || '支付失败！')
            _this.data.isPayClick = false
          }
        },
        complete: function() {
          wx.hideLoading()
        }
      })
    },

    /**
     * 微信支付
     * @param {Object} config 微信支付参数
     */
    WeChatPay: function(config, redirect) {
      // 解构数据
      let { timestamp, nonceStr, signType, paySign, orderInfo } = config
      // 微信支付参数
      let payParams = { timeStamp: timestamp, nonceStr, package: config.package, signType: signType || 'MD5', paySign }
      // const payParams = {}
      const _this = this
      if (orderInfo && orderInfo !== true) {
        wx.requestOrderPayment({
          ...payParams,
          // 需要新增的 订单 信息
          orderInfo,
          success: () => {
            _this.checkPay();
          },
          fail: (err) => {
            console.log(err);
          },
        })
      } else {
        const { senceKey } = this.data
        if (senceKey == '1177' || senceKey == '1175' || senceKey == '1176' || senceKey == '1195' || senceKey == '1191' || orderInfo) {
          wx.requestOrderPayment({
            ...payParams,
            success: () => {
              this.toRedirect();
            },
            fail: (err) => {
              console.log(err);
            },
          })
        } else {
          this.WXPay(payParams, redirect || 'home', config.is_pay_manager)
        }
      }
    },

    /**
     * 微信支付 支付管理is_pay_manager == 1是支付管理，走requestOrderPayment收银台，反之走requestPayment
     * @param {Object} payParams 微信支付参数
     * @param {String} url 请求地址
     * @param {String | Number} is_pay_manager 支付管理
     */
    WXPay: function(payParams, url, is_pay_manager = 0) {
      let urlStr = app.getNetAddresss("order.mini-app.index")
      const _this = this
      logs.info('----------WXPay>payParams 778-----------', payParams, url,is_pay_manager)
      if(is_pay_manager == 1) {
        wx.requestOrderPayment({
          ...payParams,
          success: () => {
            // _this.WXPayChild(payParams, urlStr, url);
            _this.toRedirect()
          },
          fail: (err) => {
            _this.data.isPayClick = false;
            wx.showToast({
              title: "支付失败请稍后重试",
              icon: "none",
              duration: 2000,
            });
            logs.info('----------WXPay>requestOrderPayment err-----------', err)
          }
        })
      } else {
        wx.requestPayment({
          ...payParams,
          success: () => {
            // _this.WXPayChild(payParams, urlStr, url);
            _this.toRedirect()
          },
          fail: (err) => {
            _this.data.isPayClick = false;
            wx.showToast({
              title: "支付失败请稍后重试",
              icon: "none",
              duration: 2000,
            });
            logs.info('----------WXPay>requestPayment err-----------',err)
          }
        })
      }
    },

    /**
     * 未知
     * @param {Object} payParams 微信支付参数
     * @param {String} urlStr 请求地址
     * @param {String} url 请求route
     */
    WXPayChild: function(payParams, urlStr, url) {
      const json = {
        formID: payParams.package.slice(10),
        orderId: ''
      }
      const _this = this
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: (res) => {
          let resData = res.data
          if (resData.result == 0) {
            wx.showToast({
              icon: "none",
              title: res.msg || '失败',
              duration: 1500,
            });
          }

          if (url) {
            _this.setData({
              cbHref: { cbHref: url },
            })
            _this.toRedirect()
          } else {
            wx.navigateBack({ delta: 1 })
          }
        },
      });
    },

    /**
     * 支付成功的页面跳转
     */
    toRedirect: function() {
      wx.redirectTo({
        url: this.data.redirectPath,
      })
    },
  }
})